<template>
  <div class="good-detail hiddenScroll">
    <LayoutContainer>
      <div class="detail">
        <div class="main" v-if="goodsDetail">
          <div class="detail-image">
            <v-carousel hide-delimiters progress="primary" class="images-container" v-if="goodsDetail.images">
              <template v-slot:prev="{ props }">
                <el-icon :size="20" class="hover-scale">
                  <ArrowLeft variant="elevated" @click="handleClick(props, 0)" />
                </el-icon>
              </template>
              <template v-slot:next="{ props }">
                <el-icon :size="20" class="hover-scale">
                  <ArrowRight variant="elevated" @click="handleClick(props, 1)" />
                </el-icon>
              </template>

              <!-- bug，轮播图第一张图不能v-for -->
              <v-carousel-item cover>
                <el-image class="image" @click="onBig(goodsDetail.images[0])" :src="goodsDetail.images[0]"></el-image>
              </v-carousel-item>
              <v-carousel-item v-for="(item, index) in goodsDetail.images.slice(1)" :key="index" cover>
                <el-image class="image" @click="onBig(item)" :src="item"></el-image>
              </v-carousel-item>
            </v-carousel>
          </div>
          <div class="detail-content">
            <div class="name">{{ goodsDetail.name }}</div>
            <div class="description">商品描述：{{ goodsDetail.description }}</div>
            <div style="display: flex">
              <div class="price">￥{{ decimalPointSave(goodsDetail.price) }} 元</div>
              <div class="integral" style="margin-left: 15px">∫{{ goodsDetail.integral }} 积分</div>
            </div>
            <div class="tags">
              <el-tag type="primary" v-for="tag in goodsDetail.tags">{{ tag }}</el-tag>
            </div>
            <div class="number">库存数量：{{ goodsDetail.number }}</div>
            <div class="choose-number">
              购买数量：
              <el-input-number v-model="chooseNum" :min="1" :max="goodsDetail.number > 0 ? goodsDetail.number : 1" />
            </div>
            <div class="description">配送：免运费 支持发票</div>
            <div class="operation">
              <div class="buy" @click="buy">立即购买</div>
              <div class="add-cart" @click="addCart">加入购物车</div>
            </div>
          </div>
        </div>
        <div class="comments">
          <div class="post-comment">
            <el-avatar :size="30" :src="avatar" />
            <el-input v-model="comment.newComment" style="width: 90%" placeholder="期待你的精彩评论..." maxlength="100"
              show-word-limit clearable @keyup.enter="postNewComment" />
            <el-button type="primary" @click="postNewComment">发布</el-button>
            <el-rate v-model="comment.rate" allow-half class="rate" />
          </div>
          <div class="user-comments">
            <Comment style="width: 90% !important" v-if="comments && comments.length > 0" v-for="comment in comments"
              :obj="comment" :type="`1`" @deleteComment="getAllComments()"></Comment>
            <el-empty v-else description="没有更多商品评论" />
          </div>
        </div>
      </div>
    </LayoutContainer>
  </div>
</template>

<script setup>
import { addGoodToCart, getComments, getGoodsDetail, postComment } from '@/api/shop'
import { getAvatar } from '@/api/user'
import Comment from '@/components/Comment.vue'
import LayoutContainer from '@/layout/LayoutContainer.vue'
import { startLoading, stopLoading } from '@/utils/loading'
import { decimalPointSave } from '@/utils/strutils'
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getFile } from '@/utils/fileutils'
import { defaultAvatar } from '@/common/variable'
import '@/common/variables.css'
import { ElNotification } from 'element-plus'

const route = useRoute()

const router = useRouter()

// 商品id
const id = route.params.id

// 轮播图当前图片
const currentImageNum = ref(0)

// 购买数量
const chooseNum = ref(1)

// 商品信息
const goodsDetail = ref()

// 获取商品信息
const getInfo = async () => {
  startLoading()
  const { data } = (await getGoodsDetail(id)).data
  stopLoading()
  goodsDetail.value = data
  // 将图片格式转化成blob格式，Promise.all获取所有promise的结果
  goodsDetail.value.images = await Promise.all(
    goodsDetail.value.images.map(async (image) => getFile(image)),
  )
}

// 点击轮播
const handleClick = (props, type) => {
  props.onClick()
  if (type === 0) {
    currentImageNum.value =
      currentImageNum.value - 1 < 0
        ? goodsDetail.value.images.length - 1
        : currentImageNum.value - 1
  } else {
    currentImageNum.value =
      currentImageNum.value + 1 >= goodsDetail.value.images.length ? 0 : currentImageNum.value + 1
  }
}

// 评论内容
const newComment = ref('')

// 头像
const avatar = ref(defaultAvatar)

// 评分
const comment = ref({
  newComment: '',
  rate: 3,
})

// 获取头像
const getAvatarInfo = async () => {
  avatar.value = await getAvatar()
}

// 发布评论
const postNewComment = async () => {
  startLoading()
  const res = (
    await postComment({
      recordId: id,
      content: comment.value.newComment,
      rate: comment.value.rate,
    })
  ).data
  stopLoading()

  if (res.success) {
    comment.value.newComment = ''
  } else {
    ElNotification({
      title: '错误',
      message: '发布评论失败，请稍后重试',
      type: 'error',
    })
  }
  await getAllComments()
}

// 所有评论
const comments = ref([])

// 获取所有评论
const getAllComments = async () => {
  startLoading()
  const res = (await getComments(id)).data
  stopLoading()
  comments.value = res.data
}

// 购买商品
const buy = () => {
  if (goodsDetail.value.number <= 0) {
    ElNotification({
      title: '错误',
      message: '商品已售完',
      type: 'error',
    })
    return
  }
  const chase = [
    {
      id: id,
      number: chooseNum.value,
    },
  ]
  sessionStorage.setItem('chase', JSON.stringify(chase))
  router.push('/pay')
}

// 加入购物车
const addCart = async () => {
  startLoading()
  const res = (await addGoodToCart(id)).data
  stopLoading()
  if (res.success) {
    ElNotification({
      title: '成功',
      message: '加入购物车成功',
      type: 'success',
    })
  } else {
    ElNotification({
      title: '错误',
      message: '加入购物车失败，已存在重复商品',
      type: 'error',
    })
  }
}

// 点击图片放大
const onBig = (data) => {
  ElMessageBox.alert(
    `<img src="${data}" style="max-width: 100%; height: auto; display: block; margin: 0 auto;" />`,
    '预览',
    {
      dangerouslyUseHTMLString: true,
      draggable: true,
      confirmButtonText: '关闭',
    },
  )
}

// 将图片转成可见格式
onMounted(async () => {
  // 根据id获取商品信息
  await getInfo()
  // 获取头像信息
  await getAvatarInfo()
  // 获取所有评论
  await getAllComments()
})
</script>

<style scoped less="scss">
.good-detail {
  .detail {
    width: 90%;
    margin: 0 auto;
    transition: all 0.3s;
    box-shadow: 0px 1px 5px 0px rgba(0, 0, 0, 0.1);
    background-color: var(--sub-color);

    .main {
      position: relative;

      display: flex;

      width: 90%;
      min-height: 400px;

      margin: 70px auto;
      margin-bottom: 0px;
      border-radius: 5px;

      transition: all 0.3s;

      .detail-image {
        width: 250px;
        height: 400px;
        margin: 5px 0 0 5px;
        border-radius: 5px;
        background-color: rgba(246, 243, 243, 0.1);

        .images-container {
          position: relative;

          height: 410px !important;
          border-radius: 5px;
          overflow: hidden;

          .image {
            width: 100%;
            display: block;
            height: auto;
            cursor: pointer;

            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            border-radius: 5px;
          }

          .image::before {
            content: '';
            font-family: 'Font Awesome 5 Free';
            font-weight: 900;
            color: transparent;
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            display: flex;
            justify-content: center;
            align-items: center;
            background-size: 100% 100%;
            border-radius: 5px;
            transition: background-color 0.3s;
            z-index: 1;
          }

          .image:hover::before {
            position: absolute;
            color: white;
            font-size: 1.5rem;
            background-color: rgba(0, 0, 0, 0.3);
            z-index: 5;
          }

          .hover-scale {
            width: 40px;
            height: 40px;
            cursor: pointer;
            color: transparent;
            border-radius: 40px;
            transition: all 0.5s;
          }

          .hover-scale:hover {
            color: #333;
            background-color: white;
            opacity: 0.5;
            transform: scale(1.1);
          }
        }
      }

      .detail-content {
        display: flex;
        flex-direction: column;
        gap: 10px;

        margin: 5px 0 0 15px;

        .name {
          font-size: 2rem;
        }

        .tags {
          display: flex;
          gap: 5px;
        }

        .description,
        .number,
        .choose-number {
          font-size: 14px;
          color: grey;
        }

        .price,
        .integral {
          font-size: 18px;
        }

        .price {
          color: rgb(237, 14, 62);
        }

        .integral {
          color: rgb(78.1, 141.8, 46.6);
        }

        .operation {
          position: absolute;
          bottom: 5%;

          display: flex;

          width: 75%;
          margin-left: 15px;

          .buy,
          .add-cart {
            width: 50%;
            height: 30px;
            text-align: center;
            line-height: 30px;
            color: rgb(243, 238, 238);
            font-size: 13px;
            cursor: pointer;
          }

          .buy {
            background-color: rgb(232, 31, 98);
            border-radius: 5px 0px 0px 5px;
          }

          .add-cart {
            background-color: rgb(255, 167, 41);
            border-radius: 0px 5px 5px 0px;
          }
        }
      }
    }

    .comments {
      display: flex;
      flex-direction: column;

      width: 90%;
      min-height: 200px;
      margin: 0 auto;
      margin-bottom: 15px;

      .post-comment {
        position: relative;

        display: flex;
        align-items: center;
        gap: 15px;

        margin-left: 15px;

        .rate {
          position: absolute;
          right: 6%;
          top: 100%;
        }
      }

      .user-comments {
        display: flex;
        flex-direction: column;
        align-items: center;

        margin-top: 30px;
      }
    }
  }

  .detail:hover {
    box-shadow: 0px 3px 5px 0px rgba(0, 0, 0, 0.1);
  }
}
</style>
